package de.hub.sar.itsec.sslfetcher.hosts;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;

public class FileHostProvider implements IHostsProvider {
	private static final String DELIMITER = ";";
	
	final File file;
	
	public FileHostProvider(final String path) throws FileNotFoundException {
		this.file = new File(path);
		if (!this.file.exists()
				|| !this.file.canRead()) {
			throw new FileNotFoundException();
		}
	}

	@Override
	public Iterator<Host> iterator() {
		return new HostsIterator();
	}
	
	private class HostsIterator implements Iterator<Host> {
		private BufferedReader br;
		private Host nextHost;
		
		private HostsIterator() {
			Reader reader;
			
			try {
				reader = new FileReader(file);
				this.br = new BufferedReader(reader);
				this.next();
			} catch (FileNotFoundException e) {
				this.nextHost = null;
				this.br = null;
			}
		}
		
		@Override
		public boolean hasNext() {
			return this.nextHost != null;
		}

		@Override
		public Host next() {
			Host host;
			
			host = this.nextHost;
			this.nextHost = this.getNext();
			
			return host;
		}
		
		private Host getNext() {
			String line;
			String[] split;
			
			if (this.br == null) {
				return null;
			}
			
			while (true) {
				try {
					line = this.br.readLine();
				} catch (IOException e) {
					return null;
				}
				
				if (line == null) {
					return null;
				}
				
				if (line.isEmpty()) {
					continue;
				}
				
				split = line.split(DELIMITER);
				if (split.length == 1) {
					return new Host(split[0], split[0], 443);
				}
				if (split.length == 2) {
					return new Host(split[0], split[1], 443);
				}
				if (split.length == 3) {
					return new Host(split[0], split[1], Integer.parseInt(split[2]));
				}
			}
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}
}
